package com.neusoft.databus.core.fixture;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.commons.collections.KeyValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;

import com.neusoft.databus.common.enums.DictionaryType;
import com.neusoft.databus.common.model.Dictionary;
import com.neusoft.databus.core.repository.DictionaryRepository;

import lombok.Getter;
import lombok.Setter;

/**
 * 数据初始化
 *
 * @author sunchf
 * @date 2019年3月18日 上午9:59:20
 */

@Component
@Profile("fixture")
public class DictionaryFixture implements CommandLineRunner {

    @Autowired
    private DictionaryRepository dictionaryRepository;

    @Override
    public void run(final String... args) throws Exception {
        this.syncDataOfResource();
    }

    private void syncDataOfResource() {
        //资源类型
        final List<Dictionary> dictionaries = this.dictionaryRepository
                .findByDictionaryTypeAndParentIsNull(DictionaryType.resource);
        if (dictionaries.size() <= 0) {
            final SimpleKV parent1 = new SimpleKV("0001", "供电");
            final String[] children1 =
                    {"0007,备用发电机组", "0008,新能源发电设备", "0009,高压成套柜", "0010,低压成套柜", "0011,低压配电柜", "0012,直流配电屏",
                            "0013,ATS设备", "0014,STS设备", "0015,精密配电柜", "0016,机柜PDU", "0017,变压器", "0018,蓄电池", "0019,补偿装置",
                            "0020,不间断电源", "0021,整流（直流）电源", "0022,逆变（交流）电源", "0023,直流转换电源", "0024,应急电源",
                            "0025,电力供电其他", };

            final SimpleKV parent2 = new SimpleKV("0002", "HVAC");
            final String[] children2 =
                    {"0026,水冷型机房空调", "0027,风冷型机房空调", "0028,水冷冷机", "0029,风冷冷机", "0030,冷却塔", "0031,空调室外机",
                            "0032,水泵", "0033,加湿器", "0034,新风机组", "0035,排风机组", "0036,板式换热器", "0037,暖通空调其他" };

            final SimpleKV parent3 = new SimpleKV("0003", "监控");
            final String[] children3 =
                    {"0038,电量仪", "0039,专用控制器", "0040,温湿度传感器", "0041,压力传感器", "0042,漏水传感器", "0043,入侵检测",
                            "0044,门禁控制器", "0045,视频摄像头", "0046,监控主机", "0047,监控通讯", "0048,监控其他" };

            final SimpleKV parent4 = new SimpleKV("0006", "消防");
            final String[] children4 =
                    {"0061,消防控制", "0060,消防告警", "0058,火灾温度传感器", "0062,消防其他", "0059,火灾烟雾传感器", "0057,极早期火灾探" };

            final SimpleKV parent5 = new SimpleKV("0004", "机柜");
            final String[] children5 = {"0049,机柜", "0050,机房其他", };

            final SimpleKV parent6 = new SimpleKV("0005", "IT");
            final String[] children6 = {"0052,存储设备", "0056,IT其他", "0054,交换机", "0053,路由器", "0051,服务器", };

            final Map<SimpleKV, String[]> tree = new HashMap<>();
            tree.put(parent1, children1);
            tree.put(parent2, children2);
            tree.put(parent3, children3);
            tree.put(parent4, children4);
            tree.put(parent5, children5);
            tree.put(parent6, children6);
            this.save(tree, DictionaryType.resource);
        }
        //指标单位
        final List<Dictionary> unitDictionaries = this.dictionaryRepository
                .findByDictionaryTypeAndParentIsNull(DictionaryType.unit);
        if (unitDictionaries.size() <= 0) {
            final String[] children1 =
                    {"Hz,赫兹",
                            "V,伏特",
                            "A,安培",
                            "kVA,千伏安",
                            "kW,千瓦",
                            "cosφ,cosφ",
                            "%,%",
                            "kWh,千瓦时",
                            "℃,摄氏度",
                            "Ahr,安培.小时",
                            "cmh,立方米/小时",
                            "L/s,升/秒",
                            "rpm,转每分",
                            "m,m",
                    };
            this.save(children1, DictionaryType.unit);
        }
    }

    private void save(final Map<SimpleKV, String[]> tree, final DictionaryType dictionaryType) {
        for (final Map.Entry<SimpleKV, String[]> entry : tree.entrySet()) {

            final Dictionary parent = new Dictionary();
            parent.setDictionaryType(dictionaryType);
            parent.setCode(entry.getKey().getKey());
            parent.setText(entry.getKey().getValue());
            parent.setSort(0);
            this.dictionaryRepository.save(parent);

            final List<SimpleKV> childrenKVs = Arrays.asList(entry.getValue()).stream().map(it -> {
                final String[] tuple = it.split(",");
                return new SimpleKV(tuple[0], tuple[1]);
            }).collect(Collectors.toList());

            for (int i = 0; i < childrenKVs.size(); i++) {
                final Dictionary child = new Dictionary();
                child.setDictionaryType(dictionaryType);
                child.setCode(childrenKVs.get(i).getKey());
                child.setText(childrenKVs.get(i).getValue());
                child.setSort(i);
                child.setParent(parent);
                this.dictionaryRepository.save(child);
            }
        }
    }

    private void save(final String[] dictionaries, final DictionaryType dictionaryType) {
        final List<SimpleKV> SimpleKVs = Arrays.asList(dictionaries).stream().map(it -> {
            final String[] tuple = it.split(",");
            return new SimpleKV(tuple[0], tuple[1]);
        }).collect(Collectors.toList());

        for (int i = 0; i < SimpleKVs.size(); i++) {
            final Dictionary dictionary = new Dictionary();
            dictionary.setDictionaryType(dictionaryType);
            dictionary.setCode(SimpleKVs.get(i).getKey());
            dictionary.setText(SimpleKVs.get(i).getValue());
            dictionary.setSort(i);
            this.dictionaryRepository.save(dictionary);
        }
    }

    @Getter
    @Setter
    public static class SimpleKV implements KeyValue {
        private String key;
        private String value;
        private List<SimpleKV> childrens = new ArrayList<>();

        public SimpleKV(final String key, final String value) {
            this.key = key;
            this.value = value;
        }
    }

}
